#include<stdio.h>
#include<stdlib.h>
void main() {
	int sum = 0;
	int average = 0;
	int quitThisTime = 0;
	FILE* fp;
	int studentNum;
	// take it as a string for reporting errors
	errno_t err;

	int mark[10] = { 0 };
	//printf("How many subjects: ");
	//scanf_s("%d", &k);
	//fp = fopen("stud.csv", "w");

	// Automatically create stud.csv if it is not exist
	

	while(1)
	{
		err = fopen_s(&fp, "stud.csv", "a");
		if (fp == NULL) {
			printf("\n Failed to open the file.\n");
			exit(1);
		}
		// id, m1, m2, m3
		// id, m1, m2, m3, averagegets(studentNumber[q]);
		printf("ENTER -1 ANYWHERE TO QUIT THIS PROGRAM\n");

		printf("Student number: ");
		scanf_s("%d", &studentNum);
		if (studentNum == -1)
			quitThisTime = 1;
		if (quitThisTime)
			break;
		for (int i = 0;i < 3;i++) {
			printf("Subject %d: ", i + 1);
			scanf_s("%d", &mark[i]);
			if (mark[i] == -1) {
				quitThisTime = 1;
				break;
			}
		}

		for (int i = 0; i < 3; i++)
		{
			sum += mark[i];
		}
		average = sum / 3;

		if (quitThisTime)
			break;
		// output
		fprintf(fp, "%d, %d, %d, %d, %d\n", studentNum, mark[0], mark[1], mark[2], average);
		printf("Output successfully!\n");

		// Save in realtime at a cost of speed.
		fclose(fp);
	} 
		
	
}